package influx

import (
	"context"
	influxdb2 "github.com/influxdata/influxdb-client-go/v2"
	"github.com/influxdata/influxdb-client-go/v2/api"
	"github.com/influxdata/influxdb-client-go/v2/api/write"
	"log"
	"notifications/pkg/modals"
	"time"
)

func ClientInfluxDB() *api.QueryTableResult {
	e := modals.LoadConfigInflux()
	client := influxdb2.NewClient(e.InfluxDBAddr, e.InfluxDBToken)
	writeAPI := client.WriteAPIBlocking(e.InfluxDBOrg, e.InfluxDBDatabase)
	for value := 0; value < 5; value++ {
		tags := map[string]string{
			"tagname1": "tagvalue1",
		}
		fields := map[string]interface{}{
			"field1": value,
		}
		point := write.NewPoint("measurement1", tags, fields, time.Now())
		time.Sleep(1 * time.Second) // separate points by 1 second

		if err := writeAPI.WritePoint(context.Background(), point); err != nil {
			log.Println(err)
		}
	}
	queryAPI := client.QueryAPI(e.InfluxDBOrg)
	query := `from(bucket: "lineload")
  				|> range(start: -30s)
  				|> filter(fn: (r) => r["_measurement"] == "away" or r["_measurement"] == "busy" or r["_measurement"] == "online" or r["_measurement"] == "conversations-awaiting-assigned" or r["_measurement"] == "conversations-awaiting-unassigned" or r["_measurement"] == "conversations-opened-assigned" or r["_measurement"] == "conversations-opened-unassigned" or r["_measurement"] == "conversations-solved-assigned" or r["_measurement"] == "conversations-solved-unassigned")
  				|> filter(fn: (r) => r["_field"] == "count")
  				|> filter(fn: (r) => r["line"] == "1 линия поддержки" or r["line"] == "2 линия поддержки" or r["line"] == "Опоздания" or r["line"] == "Качество и Сборка")
				|> last()`
	results, err := queryAPI.Query(context.Background(), query)
	if err != nil {
		log.Println(err)
	}

	if err := results.Err(); err != nil {
		log.Println(err)
	}
	return results
}
